import React from 'react';
import {
    observable,
    action,
    computed
} from 'mobx';
import {
    SearchAdvanced,
    ListViewPage
} from 'weaver-mobile-page';
import {
    ActionSheet,
    Tools,
    Bubble,
    Modal,
} from "weaver-mobile";
import * as api from '../../apis/resource';
import BaseStore from '../BaseStore';
import find from 'lodash/find';
import filter from 'lodash/filter';
import showTemplates from '../../components/resource/showTemplates/index';
const getLabel = Tools.getLabel;
const alert = Modal.alert;

const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
    wrapProps = {
        onTouchStart: e => e.preventDefault(),
    };
}

const conditionUrl = '/api/public/browser/condition/1'

class ResourceStore extends BaseStore {
    rowKey = 'id';
    nameKey = 'lastname';
    currentPage = 1;
    pageSize = 20;
    count = 0;
    dataTemp = {};

    mobile = '';
    telephone = '';
    email = '';

    JSAPI = ['mailto', 'openLink', 'importContacts', 'personCardSupport'];

    @observable resourceInfo = {};
    @observable catelog = [];
    @observable advanceSearchPageStore = new SearchAdvanced.Store({
        route: '/subordinate',
        id: 'advanceSearch'
    });

    @observable listViewStore = new ListViewPage.Store();

    @observable lastname = '';

    //pagination
    @observable listDatas = [];
    @observable count = 0;

    @observable showPop = false;
    @observable alllevel = false;

    @observable pageLoading = false; //隐藏导入手机

    //底部按钮组，打电话和必达功能调用的是移动模块的控制权限
    @observable hasCall = false; //是否包含打电话功能

    @observable hasBida = false; //是否包含必达功能

    @observable hasPrivateChat = false; //是够包含发送消息功能

    @observable hasmailto = false;

    @observable hasopenLink = false;

    @observable hasimportContacts = false;

    @observable haspersonCardSupport = false;

    @observable accountinfo=[];

    @observable hasRight = false;

    @observable userId = '';

    @observable authloading = false;

    @observable hasSexIcon = false;

    @observable mailAuth = false;

    @computed get fuckCall() {
        if (!this.haspersonCardSupport) {
            return 'weChart';
        }
        if (this.haspersonCardSupport && this.hasCall) {
            return 'EM';
        }
    }

    @action getResourceBaseTitle = (id) => {
        this.authloading = true;
        
        return new Promise( (resolve,reject) => {
            const params = {
                id,
                isMobx:1
            };
            api.getResourceBaseTitle(params).then(datas => {
                this.hasRight  = datas.hasRight;
                this.userId = datas.id;
                this.authloading = false;

                this.hasSexIcon = datas.result.sex;
                resolve();
            }).catch(() => reject())
        } )
    }

    @action queryResourceInfo = (id, noLoadData) => {
        if (noLoadData === '1') {
            this.pageLoading = true;
            this.Toast.loading('loading', 0);
        }

        this.hrmId = id;

        const params = {
            id
        };

        if (noLoadData === '1') {
            Object.assign(params, {
                noLoadData
            });
        }

        api.init(params).then(rs => {
            rs.map((data, index) => {
                if (data.status === '1' || data.status == null) {
                    switch (index) {
                        case 0:
                            if (data.validate && data.validate["19"]) {
                                this.mailAuth = data.validate["19"].isValidate;
                            }
                            this.convertResourceInfo(data);
                            break;
                        case 1:
                            this.catelog = data;
                            break;
                    }
                }
            });

            this.personCardSupport();

            this.Toast.hide();

            this.pageLoading = false;

            if (noLoadData === '1') this.queryResourceInfo(this.hrmId, '0');
        }, error => {
            this.Toast.hide();
        });
    }

    @action convertResourceInfo = data => {
        try {
            const {
                result,
                validate
            } = data;

            const item2 = result.find(item=>item.id === 'item2');

          const item2_account = item2 && item2.items.find(item=>item.accountinfo);

          if (item2_account) {
            this.accountinfo = item2_account.accountinfo;
          }
            const header = find(result, {
                id: 'item1'
            });

            const headerInfo = {};

            header != null && header.items.length > 0 && header.items.map(item => {
                if (item.name == 'lastname') {
                    document.title = item.value
                }
                Object.assign(headerInfo, {
                    [item.name]: item
                })
            });

            const _formInfo = filter(result, v => (!v.id && !v.hide));

            const reverse = (arr) => {
                const s = arr.splice(0, 1);

                let _arr = [];

                arr.map((item, index) => {
                    _arr.push(item);

                    if (index === 0) {
                        _arr = [..._arr, ...s]
                    }
                });

                return _arr;
            }

            const formInfo = (_formInfo.length > 1) ? reverse(_formInfo) : _formInfo;

            this.resourceInfo = {
                headerInfo,
                formInfo,
                result,
                validate,
            }

        } catch (e) {}


    }

    @computed get masterId(){
        let id;
        const result = this.accountinfo.find(info=>info.name && info.name === 'belongto');
        if (result) {
            id = result.value;
        }else{
            id=this.hrmId
        }
        return id;
    }

    @computed get isAvatarShow() {
        const {
            validate
        } = this.resourceInfo;

        let showAvatar = true;

        validate && Object.entries(validate).map(arr => {
            const [key, config] = arr;

            const {
                isValidate
            } = config;

            if (key === '36' && !isValidate) {
                showAvatar = false;
            }
        })

        return showAvatar;
    }

    @computed get sortedBarConfig() {
        const {
            result
        } = this.resourceInfo;

        const _result = this.toJS(result);

        if (!Array.isArray(_result)) return

        const item = _result.filter(r => r.id && r.id === 'item2');

        if (item.length === 0) return;

        const target = item[0].items.filter(data => data.options && Array.isArray(data.options));

        return target[0].options;
    }

    @computed get barConfig() {
        const {
            validate
        } = this.resourceInfo;

        if (!validate) return [];

        let configs = [];
        Object.entries(validate).map(arr => {
            const [key, config] = arr;

            const {
                isValidate,
                mobileUse,
                validateName
            } = config;

            if (mobileUse && isValidate) {
                const clone = {
                    ...config,
                    content: validateName,
                    text: validateName,
                    onClick: () => this.handleClick(key)
                };

                Object.assign(clone, {
                    key
                });
                configs.push(clone);
                ['validateName', 'isValidate', 'mobileUse'].map(key => {
                    delete clone[key];
                });
            }

        });

        const sortConfigs = (configs) => {
            const _configs = [];

            const sorted = this.toJS(this.sortedBarConfig);

            if (!Array.isArray(sorted)) return configs;

            sorted.map(c => {
                const {
                    validateId
                } = c;

                const target = configs.find(c => c.key === validateId);

                target && _configs.push(target);
            })

            return _configs;
        }

        return sortConfigs(configs);
    }

    @computed get datas() {
        const {
            barConfig
        } = this;

        const excludePrivateChat = (configs) => {
            return configs.filter(c => c.key !== '33')
        }

        const _barConfig = excludePrivateChat(barConfig);

        const CALL = {
            key: 'call',
            text: getLabel(507353, "打电话"),
            content: getLabel(507353, "打电话"),
            onClick: () => this.handleClick('call'),
        }

        const BIDA = {
            key: 'bida',
            text: getLabel(513223, "必达"),
            content: getLabel(513223, "必达"),
            onClick: () => this.handleClick('bida'),
        }

        const PRIVATECHAT = {
            key: 'chat',
            text: getLabel(513224, "发送消息"),
            content: getLabel(513224, "发送消息"),
            onClick: () => this.handleClick('chat'),
        }

        const EXPORT = {
            key: 'export',
            text:  getLabel(500943, "导入手机").replace(/\s\w*/g,""),
            content: getLabel(500943, "导入手机").replace(/\s\w*/g,""),
            onClick: () => this.handleClick('export'),
        };

        const CANCEL = {
            key: 'cancel',
            content: getLabel(500944, '取消'),
            onClick: () => {},
        };

        const MORE = {
            key: 'more',
            text: getLabel('17499', "更多"),
            onClick: () => this.handleClick('more'),
        }

        const EMFUNCTION_START = [PRIVATECHAT, BIDA, CALL];
        const EMFUNCTION_END = [EXPORT];
        const allFunctions = [..._barConfig, ...EMFUNCTION_END];

        allFunctions.forEach(item => {
            const {
                key
            } = item;

            if (key === "31") {
               ["content","text"].forEach(val => {
                item[val] = getLabel(513265,"发送短信")
               })
            }
        });

        ['hasPrivateChat', 'hasBida', 'hasCall'].forEach((val, index) => {
            if (this[val]) {
                allFunctions.unshift(EMFUNCTION_START[index]);
            }
        });
        if (!this.hasmailto) {
            const index = allFunctions.findIndex(item => item.key === '19');
            allFunctions.splice(index, 1);
        }
        if (!this.hasopenLink) {
            ['31', '32'].forEach(key => {
                const index = allFunctions.findIndex(item => item.key === key);
                allFunctions.splice(index, 1);
            });
        }
        if (!this.hasimportContacts) {
            const index = allFunctions.findIndex(item => item.key === 'export');
            allFunctions.splice(index, 1);
        }

        if (allFunctions.length > 4) {
            allFunctions.push(CANCEL);
            return {
                bgData: [...allFunctions.slice(0, 3), MORE],
                actionSheet: allFunctions,
            };
        } else {
            return {
                bgData: allFunctions
            }
        }

    }

    @computed get contacts() {
        const userId = this.hrmId;

        const {
            result
        } = this.resourceInfo;

        const accoutInfo = result && result.find(item => item.id === 'item2');

        let contacts;
        if (accoutInfo) {
            contacts = accoutInfo.items.find(item => item.options && item.options.lastname);
        }

        if (!contacts) return false;

        const {
            options
        } = contacts, {
            lastname,
            mobile,
            telephone,
            email
        } = options;

        return [{
            userId,
            name: lastname,
            mobile,
            telephone,
            email,
        }]
    }

    @computed get listInfo() {
        const {
            result,
            formInfo
        } = this.resourceInfo;

        if (!result || !formInfo) return [];

        const accoutInfo = result.find(item => item.id === 'item2');

        let superior, subordinate;

        if (accoutInfo) {
            const info = accoutInfo.items.find(item => item.accountinfo);
            if (info) {
                const {
                    accountinfo
                } = info;

                const managerid = accountinfo.find(item => item.name === 'managerid');
                const subordinatescount = accountinfo.find(item => item.name === 'subordinatescount');

                if (managerid) {
                    const {
                        label,
                        showName,
                        value,
                    } = managerid;

                    superior = {
                        label,
                        value: showName,
                        isHtml: true,
                        id: value,
                        labelType: 'superior'
                    }
                }

                if (subordinatescount) {
                    const {
                        label,
                        value
                    } = subordinatescount;

                    subordinate = {
                        label,
                        value: value,
                        id: this.hrmId,
                        labelType: 'subordinate',
                    }
                }
            }
        }

        const supSubRelation = formInfo.find(item => item.SupSub);

        if (!supSubRelation) {
            let items = [];
            if (subordinate) items.unshift(subordinate);
            if (superior) items.unshift(superior);

            formInfo.push({
                title: getLabel(500945, '上下级关系').replace("Guanxi","relationship"),
                items,
                SupSub: true
            });
        } else {
            if (subordinate) supSubRelation.items.unshift(subordinate);
            if (superior) supSubRelation.items.unshift(superior);
        }

        return formInfo;


    }

    @action personCardSupport = () => {
        if (!window.em) return;
        window.em.checkJsApi('personCardSupport') && window.em.personCardSupport({
            userId: this.masterId,
            success: (response) => {
                let res = (typeof response === 'string') ? JSON.parse(response) : response;

                const {
                    call,
                    ding,
                    msg,
                } = res;

                this.hasCall = call;

                this.hasBida = ding;

                this.hasPrivateChat = msg;
            },
        });
    }

    handleClick = (key) => {
        if (!window.em) return;

        const call = (params) => {
            const {
                api,
                config,
                errMsg = '操作失败'
            } = params;

            const configs = {
                fail: (argument) => {
                    Bubble.error(errMsg, 1, {
                        top: '50%',
                        color: 'red'
                    });
                }
            }

            Object.assign(configs, config);

            window.em.checkJsApi(api) && window.em[api](configs);
        }
        switch (key) {
            case '19':
                this.onMailClick(this.hrmId, () => call({
                    api: 'mailto',
                    config: {
                        mail: this.email,
                    }
                }));
                break;
            case '31':
                call({
                    api: 'openLink',
                    config: {
                        url: `/spa/sms/static4mobile/index.html#sendSms?hrmid=${this.hrmId}`,
                        openType: 2,
                        sysId: window.localStorage.emobile_ec_id
                    },
                });
                break;
            case '32':
                call({
                    api: 'openLink',
                    config: {
                        url: `/spa/workplan/static4mobile/index.html#/create?selectedUser=${this.hrmId}`,
                        openType: 2,
                        sysId: window.localStorage.emobile_ec_id
                    }
                });
                break;
            case 'chat':
                call({
                    api: 'initiatePrivateChat',
                    config: {
                        targetId: this.masterId,
                        idType: 0,
                        sysId: '',
                        draft: '',
                    }
                });
                break;
            case 'more':
                const {
                    actionSheet
                } = this.datas;

                ActionSheet.showActionSheetWithOptions({
                    options: actionSheet,
                    cancelButtonIndex: actionSheet.length - 1,
                    maskClosable: true,
                    'data-seed': 'logId',
                    wrapProps,
                })

                break;
            case 'export':
                this.contacts && call({
                    api: 'importContacts',
                    config: {
                        contacts: this.contacts,
                    }
                });
                break;
            case 'call':
                call({
                    api: 'personCardFunction',
                    config: {
                        userId: this.masterId,
                        type: 'call',
                    }
                });
                break;
            case 'bida':
                call({
                    api: 'personCardFunction',
                    config: {
                        userId: this.masterId,
                        type: 'ding',
                    }
                });
                break;
        }
    }

    onMailClick = (value, callback) => {
        alert('', <p style={{paddingTop:10}}>{getLabel(507351, '是否使用OA发邮件？')}</p>, [{
            text: getLabel(507352, '使用手机邮箱'),
            onPress: callback
        }, {
            text: getLabel(826, '确定'),
            onPress: () => window.em && window.em.openLink && window.em.openLink({
                url: `/spa/email/static4mobile/index.html#/new?fromPage=hrmCard&internaltonew=${window.encodeURI(`[{id:${value},type:"resource"}]`)}`,
                openType: 2,
                sysId: window.localStorage.emobile_ec_id
            })
        }])
    }

    @action init = (refresh = false) => {
        this.querySearchCondition();
    }

    @action querySearchCondition = () => {
        this.advanceSearchPageStore.getData({
            url: conditionUrl
        }).then(form => {
            this.doReset();
            this.cleanData();
            this.queryData(this.getQueryParams());
        });
    }

    @action doReset = () => {
        const {
            form
        } = this.advanceSearchPageStore;
        form.resetFields();
    }

    @action cleanData = () => {
        this.showPop = false;
        this.currentPage = 1;
        this.listDatas.length = 0;
    }

    getQueryParams = () => {
        let params = {
            cmd: 'search',
            mobileResourceId: this.hrmId,
            ...this.getConditionParams()
        };
        params.min = (this.currentPage - 1) * this.pageSize + 1;
        params.max = this.currentPage * this.pageSize;
        if (this.alllevel) {
            params.alllevel = 1;
        }
        return params;
    }

    getConditionParams = () => {
        const {
            form: {
                formParams
            }
        } = this.advanceSearchPageStore;
        return formParams;
    }

    @action queryData = params => {
        this.listViewStore.setState({
            loading: true
        });
        api.queryData(params).then(data => {
            const {
                datas,
                lastname
            } = data;
            if (Array.isArray(datas)) {
                this.setListData(data);
            }
            this.lastname = lastname;
        }, error => {});
    }

    @action setListData = data => {
        const {
            count,
            datas
        } = data;
        const {
            template
        } = showTemplates;
        this.count = count;
        this.listDatas = [...this.toJS(this.listDatas), ...datas];

        const dataSource = this.listViewStore.dataSource.cloneWithRows(this.toJS(this.listDatas));
        this.listViewStore.setState({
            nameKey: this.nameKey,
            rowKey: this.rowKey,
            data: this.listDatas,
            template: {
                template
            },
            dataSource,
            hasMore: datas.length > 0 && this.count >= this.pageSize,
            loading: false,
            isTable: false,
            getData: () => {}
        });
    }

    @action setShowPop = bool => this.showPop = bool;

    @action onPopoverSelectHandle = node => {
        this.alllevel = !this.alllevel;
        this.setCurrentPage(1);
        this.showPop = false;
    }

    @action setCurrentPage = idx => {
        if (idx == null)
            this.currentPage++;
        else if (idx === this.currentPage && this.currentPage != 1) {
            this.listViewStore.setState({
                hasMore: false,
                loading: false
            });
            return;
        } else {
            this.cleanData();
            this.currentPage = idx;
        }
        this.queryData(this.getQueryParams());
    }

    @action doQuickSearch = () => {
        this.initialPage = 6;
        this.cleanData();
        this.queryData(this.getQueryParams());
    }

    @action onQuickSearchChangeHandle = v => {
        const {
            form
        } = this.advanceSearchPageStore;
        form.updateField('lastname', v.toString());
    }

    @action onClearSearchCondition = () => {
        this.onQuickSearchChangeHandle('');
        this.doQuickSearch();
    }

    @action refreshData = () => {
        this.listDatas.length = 0;
        this.setCurrentPage(1);
    }

    @action setHrmId = (id) => {
        this.hrmId = id;
        this.alllevel = false;
    }

    setMobile = (mobile) => {
        this.mobile = mobile;
    }

    setTelephone = (telephone) => {
        this.telephone = telephone;
    }

    setEmail = (email) => {
        this.email = email;
    }

    @action resetDatas = () => {
        this.resourceInfo = {};
    }

    @action setCheckJsApiResults = (results) => {
        results.forEach((result, index) => {
            const api = this.JSAPI[index];
            this[`has${api}`] = result;
        })
    }



}

export const resourceStore = new ResourceStore();